package logic

import (
	"context"
	"encoding/json"
	"strconv"
	"time"
	"yktwo/models/mysql"
	"yktwo/models/redis"
	"yktwo/yktworpc/internal/svc"
	"yktwo/yktworpc/yktworpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 展示
func (l *ProductListLogic) ProductList(in *yktworpc.ProductListRequest) (*yktworpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line

	var lists []mysql.Product
	var count int64
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	atoi := strconv.Itoa(int(offset))
	get := redis.Client.Get("list" + atoi)
	mysql.DB.Debug().Model(&lists).Count(&count)
	if get.Val() == "" {
		mysql.DB.Debug().Model(&lists).Limit(int(in.Size)).Offset(int(offset)).Where("produce_name    like  ?", "%"+in.ProduceName+"%").Order("price desc").Find(&lists)
		marshal, _ := json.Marshal(&lists)
		redis.Client.Set("list"+atoi, marshal, time.Hour*24)

	} else {
		json.Unmarshal([]byte(get.Val()), &lists)
	}

	var liststruct []*yktworpc.ProductListStruct
	for _, list := range lists {
		price := yktworpc.ProductListStruct{
			ProduceCode: list.ProduceCode,
			Img:         list.Img,
			ProduceName: list.ProduceName,
			Price:       float32(list.Price),
			Store:       int64(list.Store),
			Status:      int64(list.Status),
			UserId:      int64(list.UserId),
		}
		liststruct = append(liststruct, &price)
	}

	return &yktworpc.ProductListResponse{List: liststruct, Total: count}, nil
}
